package com.udp;

import java.io.IOException;
import java.net.*;

public class Receive01 {
    public static void main(String[] args) throws IOException {
        //创建一个datagramsocket对象,在8888端口接收数据
        DatagramSocket datagramSocket=new DatagramSocket(8888);
        //构建datagrampacket对象接收数据
        byte []bytes=new byte[1024];
        DatagramPacket datagramPacket=new DatagramPacket(bytes,bytes.length);
        //调用方法
        datagramSocket.receive(datagramPacket);
        //拆包,取数据,显示
        int len=datagramPacket.getLength();
        byte[] buf=datagramPacket.getData();
        System.out.println("收到消息"+new String(buf,0,len));
        //回复
        String message="nice to meet you";//回复的消息
        byte[] mes=message.getBytes();
            //打包
        DatagramPacket packet = new DatagramPacket(mes, mes.length, InetAddress.getLocalHost(), 9999);
        //发送消息
        datagramSocket.send(packet);
        //关闭
        datagramSocket.close();

    }
}
